package xterm

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

const (
	BLACK = iota
	RED
	GREEN
	YELLOW
	BLUE
	MAGENTA
	CYAN
	WHITE
)

var foreColor = []string{
	"\x1b[38;5;8m",
	"\x1b[38;5;9m",
	"\x1b[38;5;10m",
	"\x1b[38;5;11m",
	"\x1b[38;5;12m",
	"\x1b[38;5;13m",
	"\x1b[38;5;14m",
	"\x1b[38;5;15m",
}

var backColor = []string{
	"\x1b[48;5;0m",
	"\x1b[48;5;1m",
	"\x1b[48;5;2m",
	"\x1b[48;5;3m",
	"\x1b[48;5;4m",
	"\x1b[48;5;5m",
	"\x1b[48;5;6m",
	"\x1b[48;5;7m",
}

type TermColor struct {
}

var termColor = &TermColor{}
var Print = fmt.Print
var Println = fmt.Println
var Printf = fmt.Printf

func (tc *TermColor) Reset() *TermColor {
	fmt.Print("\x1b[0m")
	return tc
}

func (tc *TermColor) Color(color int) *TermColor {
	fmt.Print(foreColor[color])
	return tc
}

func (tc *TermColor) BackColor(color int) *TermColor {
	fmt.Print(backColor[color])
	return tc
}

func (tc *TermColor) Print(args ...interface{}) *TermColor {
	fmt.Print(args...)
	return tc
}

func (tc *TermColor) Println(args ...interface{}) *TermColor {
	fmt.Println(args...)
	return tc
}

func (tc *TermColor) Printf(format string, args ...interface{}) *TermColor {
	fmt.Printf(format, args...)
	return tc
}

func Color(color int) *TermColor {
	return termColor.Color(color)
}

func BackColor(color int) *TermColor {
	return termColor.BackColor(color)
}

func Reset() *TermColor {
	return termColor.Reset()
}

func Red() *TermColor {
	return termColor.Color(RED)
}

func Green() *TermColor {
	return termColor.Color(GREEN)
}

func Yellow() *TermColor {
	return termColor.Color(YELLOW)
}

func Blue() *TermColor {
	return termColor.Color(BLUE)
}

func Magenta() *TermColor {
	return termColor.Color(MAGENTA)
}

func Cyan() *TermColor {
	return termColor.Color(CYAN)
}

func White() *TermColor {
	return termColor.Color(WHITE)
}

//=============================================================================

func GetInput(prompt string) string {
	fmt.Print(prompt)
	s, err := bufio.NewReader(os.Stdin).ReadString('\n')
	if err != nil {
		panic(err)
	}

	return strings.TrimSpace(s)
}
